<?php

namespace admin\modules\pub\controllers;

use common\components\wtools\tools\FileHelper;
use common\models\db\BaseAreas;
use common\models\db\Files;
use yii\web\Controller;
use yii\web\Response;

class AjaxController extends Controller
{
    public $enableCsrfValidation = false;

    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return true;
        } else {
            return false;
        }
    }

    public function actionAreaSel($q = null, $level = null)
    {
        $query = BaseAreas::find()->select('id, merger_name as text');
        $out = ['results' => ['id' => '', 'text' => '']];
        if ($q) {
            $query->andFilterWhere(['like', 'merger_name', $q]);
        }
        if ($level !== null) {
            $query->andFilterWhere(['level' => $level]);
        }
        $query->andFilterWhere(['not in', 'id', BaseAreas::getGangAoTaiProIds()]);
        $data = $query->limit(10)->asArray()->all();
        $out['results'] = array_values($data);
        return $out;
    }

    public function actionWangUploadImages()
    {
        $data = [];
        foreach ($_FILES as $k => $v) {
            $url = \Yii::$app->fs->uploadByTmpFile($v);
            $item = ['url' => $url];
            $item['alt'] = '';
            $item['href'] = '';
            $data[] = $item;
        }
        return [
            'errno' => 0,
            'data' => $data,
        ];
    }

    public function actionWangUploadVideo()
    {
        if (count($_FILES) > 1) {
            return [
                'errno' => 1,
                'message' => "一次最多上传一个视频",
            ];
        }
        foreach ($_FILES as $k => $v) {
            $tmpVideo = $v;
        }
        $F = $tmpVideo['tmp_name'];
        $pathInfo = pathinfo($tmpVideo['name']);
        $ext = $pathInfo['extension'];

        if (strtolower($ext) != 'mp4') {
            $tmpDir = \Yii::getAlias('@common/runtime/ffmpeg-tmp');
            if (!is_dir($tmpDir)) FileHelper::createDirectory($tmpDir);
            $out = $tmpDir.DIRECTORY_SEPARATOR.$pathInfo['filename'].".mp4";
            $mimeType = \Yii::$app->wMimeTypes->getMimeType($ext);
            if ('video/' == substr($mimeType, 0, 6)) {
                $exec = <<<EXEC
ffmpeg -i {$F} -vcodec h264 {$out} -y
EXEC;
                exec($exec);
                if (!file_exists($out)) {
                    return [
                        'errno' => 1,
                        'message' => "视频转码失败",
                    ];
                }
                $F = $out;
            } else {
                return [
                    'errno' => 1,
                    'message' => "非视频格式",
                ];
            }
        }

        $oss = \Yii::$app->ossWy;
        $prefix = 'supplier/files/'.date('Ym/');
        $filename = str_random(16).date("dHis").".mp4";
        $ossPath = $prefix.$filename;
        $oss->upload($ossPath, $F);
        $url = $oss->getCdnUrl($ossPath);
        $item = ['url' => $url];
        unlink($F);
        return [
            'errno' => 0,
            'data' => $item,
        ];
    }

    public function actionKartikFileInputUpload()
    {
        if (\Yii::$app->request->isPost) {
            return json_encode(['success' => false, 'error' => '上传失败']);
        }
        return json_encode(['success' => false, 'error' => '无效的请求']);
    }

    public function actionUploadCover()
    {
//        dd($_FILES['file']);
        $url = \Yii::$app->fs->uploadByTmpFile($_FILES['file']);
        return [
            'code' => 200,
            'url' => $url,
        ];
    }
}
